﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Qr.Servce {
    public class QrCode {
        public string Ticket { get; set; }
        public int ExpireSeconds { get; set; }
        public string CodeUrl {
            get {
                return
                    String.Format("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={0}", this.Ticket);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="sceneId"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private static QrCode GetCode(string accessToken, string sceneId, object item) {
            string url = String.Format("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}", accessToken);

            JavaScriptSerializer js = new JavaScriptSerializer();
            string json = js.Serialize(item);

            string back = HttpUtility.Post(url, json);
            Dictionary<string, string> dic =
                js.Deserialize<Dictionary<string, string>>(back);

            QrCode code = null;
            if (dic.Keys.Contains("expire_seconds")) {
                code = new QrCode {
                    Ticket = dic["ticket"],
                    ExpireSeconds = Convert.ToInt32(dic["expire_seconds"])
                };
            }
            else {
                code = new QrCode {
                    Ticket = dic["ticket"]
                };
            }


            return code;
        }

        /// <summary>
        /// 临时二维码
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="sceneId"></param>
        /// <returns></returns>
        public static QrCode GetTemporary(string accessToken, string sceneId) {
            var item = new {
                expire_seconds = 1800,
                action_name = "QR_SCENE",
                action_info = new {
                    scene = new {
                        scene_id = sceneId
                    }
                }
            };
            return GetCode(accessToken, sceneId, item);
        }

        /// <summary>
        /// 永久二维码
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="sceneId"></param>
        /// <returns></returns>
        public static QrCode GetPermanent(string accessToken, string sceneId) {
            var item = new {
                action_name = "QR_LIMIT_SCENE",
                action_info = new {
                    scene = new {
                        scene_id = sceneId
                    }
                }
            };
            return GetCode(accessToken, sceneId, item);
        }

    }
}